﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using BaseText;

public partial class WorkTime_WorkTimeDate : System.Web.UI.Page
{
    private Srvtools.WebDataSet dsAccTime;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //InitializeComponent();

            //Master.DataSource = WMaster;

            MasterPage_MasterPage mpg = (MasterPage_MasterPage)this.Page.Master;
            mpg.HelpHref = "";
            mpg.PageName = "工龄维护";
            mpg.PicUrl = "";
            mpg.IntiBar();
        }
    }

    private void InitializeComponent()
    {
        System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(WorkTime_WorkTimeDate));
        this.dsAccTime = new Srvtools.WebDataSet();
        ((System.ComponentModel.ISupportInitialize)(this.dsAccTime)).BeginInit();
        // 
        // WMaster
        // 
        this.dsAccTime.Active = true;
        this.dsAccTime.AlwaysClose = false;
        this.dsAccTime.PacketRecords = 0;
        this.dsAccTime.Position = -1;
        this.dsAccTime.RemoteName = "Common.InfoInti";
        this.dsAccTime.ServerModify = false;
        ((System.ComponentModel.ISupportInitialize)(this.dsAccTime)).EndInit();
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        New_DataBind();
    }

    private void New_DataBind()
    {
        string strDep = dptlist.SelectDepmanetId;
        if (strDep == null || strDep == "" || strDep == "0")
        {
            strDep = " != 0";
        }
        else
        {
            strDep = " like '" + strDep + "%' ";

        }



        StringBuilder sbr = new StringBuilder();
        sbr.Append("select Employees.EmployeeID,EmpName,Accession,WorkTimeDate,Department.DepartmentName from Employees");
        //sbr.Append(" left join Contract on (Contract.EmployeeID=Employees.EmployeeID)");
        sbr.Append(" left join Department on (Employees.DepartmentId=Department.DepartmentId)");
        sbr.Append(" where Employees.EmpStatus=1 And Department.DepartmentId " + strDep);
        sbr.Append(" order by Employees.EmployeeID");

        InitializeComponent();

        DataSet ds = dsAccTime.Execute(sbr.ToString());
        wgvMaster.DataSource = ds.Tables[0];
        wgvMaster.DataBind();
    }

    protected void BatchYear_Click(object sender, EventArgs e)
    {
        string Empid;
        ArrayList sqlarr = new ArrayList();
        for (int i = 0; i < wgvMaster.Rows.Count; i++)
        {
            //Srvtools.WebDateTimePicker AddAccTime = (Srvtools.WebDateTimePicker)wgvMaster.Rows[i].FindControl("AddAccTime");
            ZLTextBox zt = (ZLTextBox)wgvMaster.Rows[i].FindControl("DoDay");
            //Label AccTime = (Label)wgvMaster.Rows[i].FindControl("AccTime");
            if (zt.Text.Trim() != null)
            {
                Empid = wgvMaster.Rows[i].Cells[0].Text.Trim();
                //string time = GetYearByMonth(DateTime.Now, zt.Text);
                //year = reGeyWorkTime(Anum);
                sqlarr.Add("update Employees set WorkTimeDate = '" + GetYearByMonth(DateTime.Now, zt.Text.Trim()) + "' where EmployeeId=" + Empid);
            }
        }

        object[] objParm = new object[] { sqlarr };
        object[] ret = Srvtools.CliUtils.CallMethod("Common", "SqlTran", objParm);

        if ((bool)ret[1])
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('全部导入成功！');", true);
        }
        else
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('全部导入失败！');", true);
        }


        New_DataBind();
    }

    protected void wgvMaster_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DataRowView drv = (DataRowView)e.Row.DataItem;

            Srvtools.WebDateTimePicker wdp = (Srvtools.WebDateTimePicker)e.Row.FindControl("AddAccTime");
            ZLTextBox zt = (ZLTextBox)e.Row.FindControl("DoDay");
            DateTime wtd = new DateTime();

            if (drv["WorkTimeDate"] != null && drv["WorkTimeDate"].ToString() != "")
            {

                try
                {
                    wtd = Convert.ToDateTime(drv["WorkTimeDate"]);
                }
                catch
                {
                    if (drv["Accession"] == null || drv["Accession"].ToString() == "")
                    {
                        wtd = DateTime.Now;
                    }
                    else
                    {
                        wtd = Convert.ToDateTime(drv["Accession"]);
                    }
                }

                //wtd = Convert.ToDateTime(drv["WorkTimeDate"]);

                ((Label)e.Row.FindControl("AccTime")).Text = GetWorkTime(wtd);

                //wdp.Text = wtd.ToString("yyyy-MM-dd");

                //zt.Text = (DateTime.Now.Year - Convert.ToInt32(drv["WorkTimeDate"])).ToString();
            }
            else
            {
                if (drv["Accession"].ToString() != "")
                {
                    wtd = Convert.ToDateTime(drv["Accession"]);
                    //zt.Text = (DateTime.Now.Year - Convert.ToDateTime(drv["Accession"]).Year).ToString();


                }

            }

            zt.Text = toResult(wtd, DateTime.Now, "m")[0].ToString();

        }
    }

    public int[] toResult(DateTime d1, DateTime d2, string type)
    {
        #region 数据初始化
        DateTime max;
        DateTime min;
        int year;
        int month;
        int tempYear, tempMonth;
        if (d1 > d2)
        {
            max = d1;
            min = d2;
        }
        else
        {
            max = d2;
            min = d1;
        }
        tempYear = max.Year;
        tempMonth = max.Month;
        if (max.Month < min.Month)
        {
            tempYear--;
            tempMonth = tempMonth + 12;
        }
        year = tempYear - min.Year;
        month = tempMonth - min.Month;
        #endregion
        #region 按条件计算
        if (type == "d")
        {
            TimeSpan ts = max - min;
            return new int[] { ts.Days };
        }
        if (type == "m")
        {
            return new int[] { month + year * 12 };
        }
        if (type == "y")
        {
            return new int[] { year };
        }
        return new int[] { year, month };
        #endregion
    }

    private string GetYearByMonth(DateTime dt, string month)
    {
        int tempYear = dt.Year;
        int tempmonth = dt.Month;
        DateTime NewDT = Convert.ToDateTime(tempYear + "-" + tempmonth + "-1");
        return NewDT.AddMonths(Convert.ToInt32(month) * -1).ToString("yyyy-MM-dd"); ;
    }

    private string GetWorkTime(DateTime wtd)
    {
        try
        {
            TimeSpan ts1 = new TimeSpan(wtd.Ticks);
            TimeSpan ts2 = new TimeSpan(DateTime.Now.Ticks);
            TimeSpan ts = ts1.Subtract(ts2).Duration();

            float day = ts.Days;
            return (day / 365).ToString("f1");

        }
        catch
        {
            return "0";
        }
    }

    private string reGetWorkTime(string Year)
    {
        return (Convert.ToInt32(DateTime.Now.Year) - Convert.ToInt32(Year)).ToString();
    }

}
